package com.ym.utils.html;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BlackListValidateUtil5 {
    private static final String blacklistStr;
    private static final String BLACKLIST_STR_NO_ESCAPE_CHARACTER;

    public BlackListValidateUtil5() {
    }

    public static boolean checkByBlack(String value) {
        if (value != null && value.length() != 0) {
            Pattern regex = Pattern.compile(blacklistStr);
            return regex.matcher(value).find();
        } else {
            return true;
        }
    }

    public static String handleByBlackWithEscape(String value) {
        if (value != null && value.length() != 0) {
            value = escapeValue(value);
            Pattern regex = Pattern.compile(BLACKLIST_STR_NO_ESCAPE_CHARACTER);
            Matcher matcher = regex.matcher(value);
            if (matcher.find()) {
                value = matcher.replaceAll("");
            }
            return value;
        } else {
            return value;
        }
    }
    //中英文省略号、\、空格（非转义）
    private static String escapeValue(String value) {
        return value != null && value.length() != 0 ? value.replaceAll("&", "&amp;")
                //.replaceAll("\"", "&quot;")
                .replaceAll("\\(", "&#40;")
                .replaceAll("\\)", "&#41;")
                .replaceAll(">", "&gt;")
                .replaceAll("<", "&lt;") : value;
        //.replaceAll("", "&nbsp;")
    }

    static {
        StringBuffer commonList = new StringBuffer();
        commonList.append("xss|script|style|javascript|abstract|eval|exec|iframe|link|href|src|alert|function|object|(\\.{6}|\\.{3})");
        commonList.append("|onload|onun|onclick|onerror|onmousemove|onprerender|ondatabinding|ondbclick|ondisposed|oninit");
        commonList.append("|onmousedown|onmouseout|onmouseup|onmouseenter|onmouseover|onkeydown|onkeypress|onkeyup|submit|onfocus");
        //commonList.append("|iframe|frame|input|button|table|td|th|tr|button|em|div|li|html");
        commonList.append("|delete|select|update|drop|netlocalgroup administrators|net user|truncate|where|xp_cmdshell|char");
        String escapeChar = "|&quot;|&gt;|&lt;|&nbsp;|&#39;|&amp;";
        String specialChar = "|[\\s ]|\r|\n|\t|`|~|!|@|#|\\$|%|\\^|&|\\*|\\(|\\)|_|\\+|=|\\[|\\]|\\{|\\}|\\||\"|'|:|<|>|,|;|\\?|\\\\|/|\\.";
        String specialCharWithNoEscapeCha = "[\\s ]|\r|\n|\t|`|~|!|@|#|\\$|%|\\^|\\*|\\(|\\)|_|\\|;|\\?|\\\\|/|\\.";
        blacklistStr = commonList.toString().concat(specialChar).concat(escapeChar);
        BLACKLIST_STR_NO_ESCAPE_CHARACTER = commonList.toString().concat(specialCharWithNoEscapeCha);
    }
}
